package com.wanfajie.smsdistribute.ui.contacts_picker

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.provider.ContactsContract
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.SearchView
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.wanfajie.smsdistribute.R
import com.wanfajie.smsdistribute.common.activity.BaseActivity
import com.wanfajie.smsdistribute.common.adapter.CheckedRecyclerAdapter
import com.wanfajie.smsdistribute.common.adapter.SearchRecyclerAdapter
import com.wanfajie.smsdistribute.common.adapter.SlideLeadRecyclerAdapter
import com.wanfajie.smsdistribute.util.HanYuComparator
import com.wanfajie.smsdistribute.util.pinyinInitial
import com.wanfajie.smsdistribute.util.toast
import kotlinx.android.synthetic.main.activity_contacts.*

class ContactsPickerActivity : BaseActivity() {

    companion object {
        private const val TAG = "ContactsPickerActivity"

        const val EXTRA_KEY_NAME = "name_array"
        const val EXTRA_KEY_NUMBER = "phone_array"
    }

    private lateinit var mSearchView: SearchView
    private val ctx : Context = this
    private val mCheckableAdapter by lazy {
        val adapter = object : SlideLeadRecyclerAdapter<Pair<String, String>>(
                this, emptyList(), R.layout.list_item_phone_number,
                R.id.checkbox, R.id.lead, View.GONE, { it.first }
        ) {
            override fun processViewHolder(p0: CheckedViewHolder, p1: Pair<String, String>) {
                super.processViewHolder(p0, p1)
                p0.get<TextView>(R.id.item_name).text = p1.first
                p0.get<TextView>(R.id.item_small_name).text = p1.second
            }
        }

        adapter.setOnClickListener { updateSelectedCountTitle() }
        adapter
    }

    private val mAdapter by lazy {
        val factory: () -> ForegroundColorSpan = {
            ForegroundColorSpan(resources.getColor(R.color.colorAccentBlack))
        }
        object : SearchRecyclerAdapter<Pair<String, String>, CheckedRecyclerAdapter.CheckedViewHolder>(
                mCheckableAdapter,
                factory,
                arrayOf(R.id.item_name, R.id.item_small_name)
        ) {
            override fun filter(index: Int, item: Pair<String, String>): Boolean {
                return keyword.isEmpty()
                        || item.first.contains(keyword, ignoreCase = true)
                        || item.second.contains(keyword, ignoreCase = true)
                        || item.first.pinyinInitial.contains(keyword, ignoreCase = true)
            }

            override fun highlight(str: CharSequence): SpannableString {
                return highlight(str, SearchRecyclerAdapter.HIGHLIGHT_HANYU_INDEX_GENE)
            }
        }
    }

    override val requiredPermissions: Array<String>? = arrayOf(Manifest.permission.READ_CONTACTS)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_contacts)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowTitleEnabled(false)

        val layoutManager = LinearLayoutManager(ctx)
        layoutManager.orientation = OrientationHelper.VERTICAL
        rv_telephone_list.layoutManager = layoutManager
        rv_telephone_list.addItemDecoration(DividerItemDecoration(this, OrientationHelper.VERTICAL))
        rv_telephone_list.adapter = mAdapter

        slide_index.setTextViewDialog(slide_index_dialog)
        slide_index.setOnItemSlideListener(mCheckableAdapter)
    }

    override fun onAllPermissionsGranted() {
        val contacts = readContacts()
        Log.i(TAG, "Contacts Count: ${contacts.size}")

        mCheckableAdapter.setItems(contacts)
    }

    private fun updateSelectedCountTitle() {
        val count = mCheckableAdapter.getCheckedCount()
        if (count == 0) {
            supportActionBar?.setDisplayShowTitleEnabled(false)
        } else {
            supportActionBar?.setDisplayShowTitleEnabled(true)
            supportActionBar?.title = getString(R.string.checked_item_count, count)
        }
    }

    private fun readContacts() : List<Pair<String, String>> {
        val cur = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null)
        val telList = ArrayList<Pair<String, String>>()

        while (cur.moveToNext()) {
            val name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
            val contactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID))
            val contactIdFieldName = ContactsContract.CommonDataKinds.Phone.CONTACT_ID

            val phoneCur = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    "$contactIdFieldName = ?", arrayOf(contactId), null)

            while (phoneCur.moveToNext()) {
                val phoneIdx = phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                val tel = phoneCur.getString(phoneIdx)
                        .replace(" ", "")
                        .replace("-", "")
                telList.add(name to tel)
            }
            phoneCur.close()
        }

        cur.close()
        telList.sortWith(compareBy(HanYuComparator()) { it.first })
        return telList
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_tel_picker, menu)
        menu?.let {
            val searchItem = it.findItem(R.id.search)
            mSearchView = searchItem.actionView as SearchView
            mSearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
                override fun onQueryTextChange(p0: String?): Boolean = false
                override fun onQueryTextSubmit(p0: String?): Boolean {
                    val kw = p0 ?: ""
                    mAdapter.search(kw)
                    mCheckableAdapter.isShowLead = kw.isEmpty()
                    return true
                }
            })
            mSearchView.setOnCloseListener {
                mAdapter.search("")
                mCheckableAdapter.isShowLead = true
                slide_index.visibility = View.VISIBLE
                false
            }

            mSearchView.setOnSearchClickListener {
                slide_index.visibility = View.GONE
            }
        }
        return true
    }

    private fun returnResultFinish() {
        if (mCheckableAdapter.getCheckedCount() == 0) {
            toast("没有选择联系人")
            return
        }

        val intent = Intent()

        val names = arrayListOf<String>()
        val phones = arrayListOf<String>()
        mCheckableAdapter.getCheckedItemList().forEach {
            names.add(it.first)
            phones.add(it.second)
        }
        intent.putStringArrayListExtra(EXTRA_KEY_NAME, names)
        intent.putStringArrayListExtra(EXTRA_KEY_NUMBER, phones)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item == null) return super.onOptionsItemSelected(item)

        when (item.itemId) {
            android.R.id.home -> {
                setResult(Activity.RESULT_CANCELED)
                finish()
            }
            R.id.select_all -> {
                val checked = mCheckableAdapter.getCheckedItemList()
                val checkedAllSearch = checked.containsAll(mAdapter.items)
                mCheckableAdapter.setChecked(!checkedAllSearch, mAdapter.items)
                updateSelectedCountTitle()
            }
            R.id.done -> returnResultFinish()
            else -> return false
        }

        return true
    }

    override fun onBackPressed() {
        when {
            !mSearchView.isIconified -> mSearchView.isIconified = true
            else -> super.onBackPressed()
        }
    }
}